package com.ydzt.fanka.server.space.broadcast;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.ydzt.fanka.server.init.InitData;
import com.ydzt.fanka.server.persistence.BufferStore;
import com.ydzt.fanka.server.utils.IOUtil;
import com.ydzt.fanka.server.utils.NetUtil;

/*
 * 此线程将broadcast文件夹中的报文发送至报文所指节点
 * */
public class BroadCastServer extends Thread{
	static Logger logger = Logger.getLogger(BroadCastServer.class.getName());
	public void run(){
		while(true){
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			File f = new File(InitData.broadcastdir);
			if(f != null){
				int count = f.listFiles().length;
				if(count > 0){
					logger.info("broadcast文件夹中 未发送报文有  " + count + "  个");
				}
				if(count != 0){
					try {
						File currentFile = f.listFiles()[0];
						byte[] pkg = IOUtil.toByteArrayTraditional(currentFile.getAbsolutePath());
						
						if(0 == NetUtil.synSendMsg(pkg)){
							logger.info("进行广播");
							if(0 == BufferStore.writePackageIntoBroadcastBackup(pkg)){
								currentFile.delete();
							}
						}
						
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				else{
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
